const express = require('express')
const cors = require('cors')
const jwt = require('jsonwebtoken')

const app = express()
const PORT = 3000
const JWT_SECRET = 'your-secret-key-change-in-production'

// 中间件
app.use(
  cors({
    origin: ['http://localhost:5173', 'http://127.0.0.1:5173'],
    credentials: true
  })
)
app.use(express.json())

// 内存存储 - 模拟数据库
let users = [
  {
    id: 1,
    username: 'admin',
    email: 'admin@example.com',
    password: 'admin123', // 实际应用中应该加密
    nickname: '管理员',
    avatar: '/avatars/admin.jpg',
    role: 'admin',
    created_at: new Date('2024-01-01'),
    updated_at: new Date()
  },
  {
    id: 2,
    username: 'reader',
    email: 'reader@example.com',
    password: '123456',
    nickname: '读者',
    avatar: '/avatars/reader.jpg',
    role: 'user',
    created_at: new Date('2024-01-02'),
    updated_at: new Date()
  }
]

let novels = [
  {
    id: 1,
    title: '修仙传说',
    author: '云中子',
    cover: '/covers/novel1.jpg',
    description: '一个普通少年的修仙之路，从凡人到仙人的传奇故事...',
    category: '玄幻',
    status: 'ongoing',
    word_count: 1500000,
    chapter_count: 300,
    rating: 4.8,
    views: 125000,
    favorites: 8500,
    created_at: new Date('2024-01-01'),
    updated_at: new Date()
  },
  {
    id: 2,
    title: '都市重生',
    author: '时光倒流',
    cover: '/covers/novel2.jpg',
    description: '重生回到十年前，这一次他要改写命运...',
    category: '都市',
    status: 'completed',
    word_count: 2000000,
    chapter_count: 400,
    rating: 4.6,
    views: 98000,
    favorites: 6200,
    created_at: new Date('2024-01-05'),
    updated_at: new Date()
  }
]

let chapters = [
  {
    id: 1,
    novel_id: 1,
    title: '第一章 初入仙门',
    content:
      '天色微明，云雾缭绕的青山之中，一座古老的仙门若隐若现...\n\n这里是内容的开始，一个普通少年即将踏上修仙之路...',
    chapter_number: 1,
    word_count: 3500,
    is_free: true,
    created_at: new Date('2024-01-01'),
    updated_at: new Date()
  },
  {
    id: 2,
    novel_id: 1,
    title: '第二章 拜师学艺',
    content:
      '经过一夜的思考，少年决定正式拜师学艺...\n\n师父是一位白发苍苍的老者，眼中却闪烁着智慧的光芒...',
    chapter_number: 2,
    word_count: 4200,
    is_free: true,
    created_at: new Date('2024-01-02'),
    updated_at: new Date()
  }
]

// 工具函数
const generateToken = user => {
  return jwt.sign(
    {
      id: user.id,
      username: user.username,
      email: user.email,
      role: user.role
    },
    JWT_SECRET,
    { expiresIn: '7d' }
  )
}

const verifyToken = (req, res, next) => {
  const token = req.headers.authorization?.replace('Bearer ', '')

  if (!token) {
    return res.status(401).json({ success: false, message: '未提供认证令牌' })
  }

  try {
    const decoded = jwt.verify(token, JWT_SECRET)
    req.user = decoded
    next()
  } catch (error) {
    return res.status(401).json({ success: false, message: '无效的认证令牌' })
  }
}

// API 路由

// 健康检查
app.get('/api/health', (req, res) => {
  res.json({
    success: true,
    message: '服务器运行正常',
    timestamp: new Date().toISOString(),
    mode: 'fallback-memory-storage'
  })
})

// 用户认证
app.post('/api/auth/register', (req, res) => {
  const { username, email, password, nickname } = req.body

  // 检查用户是否已存在
  const existingUser = users.find(
    u => u.username === username || u.email === email
  )
  if (existingUser) {
    return res.status(400).json({
      success: false,
      message: '用户名或邮箱已存在'
    })
  }

  // 创建新用户
  const newUser = {
    id: users.length + 1,
    username,
    email,
    password, // 实际应用中应该加密
    nickname: nickname || username,
    avatar: '/avatars/default.jpg',
    role: 'user',
    created_at: new Date(),
    updated_at: new Date()
  }

  users.push(newUser)

  // 生成token
  const token = generateToken(newUser)

  // 返回用户信息（不包含密码）
  const { password: _, ...userInfo } = newUser

  res.json({
    success: true,
    message: '注册成功',
    data: {
      user: userInfo,
      token
    }
  })
})

app.post('/api/auth/login', (req, res) => {
  const { username, password } = req.body

  // 查找用户（支持用户名或邮箱登录）
  const user = users.find(
    u =>
      (u.username === username || u.email === username) &&
      u.password === password
  )

  if (!user) {
    return res.status(401).json({
      success: false,
      message: '用户名或密码错误'
    })
  }

  // 生成token
  const token = generateToken(user)

  // 返回用户信息（不包含密码）
  const { password: _, ...userInfo } = user

  res.json({
    success: true,
    message: '登录成功',
    data: {
      user: userInfo,
      token
    }
  })
})

// 获取用户信息
app.get('/api/user/profile', verifyToken, (req, res) => {
  const user = users.find(u => u.id === req.user.id)
  if (!user) {
    return res.status(404).json({
      success: false,
      message: '用户不存在'
    })
  }

  const { password: _, ...userInfo } = user
  res.json({
    success: true,
    data: userInfo
  })
})

// 小说相关API
app.get('/api/novels', (req, res) => {
  const { page = 1, limit = 10, category, status, search } = req.query

  let filteredNovels = [...novels]

  // 分类筛选
  if (category && category !== 'all') {
    filteredNovels = filteredNovels.filter(novel => novel.category === category)
  }

  // 状态筛选
  if (status) {
    filteredNovels = filteredNovels.filter(novel => novel.status === status)
  }

  // 搜索
  if (search) {
    filteredNovels = filteredNovels.filter(
      novel =>
        novel.title.includes(search) ||
        novel.author.includes(search) ||
        novel.description.includes(search)
    )
  }

  // 分页
  const startIndex = (page - 1) * limit
  const endIndex = startIndex + parseInt(limit)
  const paginatedNovels = filteredNovels.slice(startIndex, endIndex)

  res.json({
    success: true,
    data: {
      novels: paginatedNovels,
      pagination: {
        page: parseInt(page),
        limit: parseInt(limit),
        total: filteredNovels.length,
        pages: Math.ceil(filteredNovels.length / limit)
      }
    }
  })
})

app.get('/api/novels/:id', (req, res) => {
  const novel = novels.find(n => n.id === parseInt(req.params.id))

  if (!novel) {
    return res.status(404).json({
      success: false,
      message: '小说不存在'
    })
  }

  res.json({
    success: true,
    data: novel
  })
})

// 章节相关API
app.get('/api/novels/:id/chapters', (req, res) => {
  const novelId = parseInt(req.params.id)
  const novelChapters = chapters.filter(c => c.novel_id === novelId)

  res.json({
    success: true,
    data: novelChapters.map(chapter => ({
      id: chapter.id,
      title: chapter.title,
      chapter_number: chapter.chapter_number,
      word_count: chapter.word_count,
      is_free: chapter.is_free,
      created_at: chapter.created_at,
      updated_at: chapter.updated_at
    }))
  })
})

app.get('/api/chapters/:id', (req, res) => {
  const chapter = chapters.find(c => c.id === parseInt(req.params.id))

  if (!chapter) {
    return res.status(404).json({
      success: false,
      message: '章节不存在'
    })
  }

  res.json({
    success: true,
    data: chapter
  })
})

// 分类列表
app.get('/api/categories', (req, res) => {
  const categories = ['玄幻', '都市', '历史', '科幻', '武侠', '言情', '悬疑']
  res.json({
    success: true,
    data: categories
  })
})

// 404 处理
app.use('*', (req, res) => {
  res.status(404).json({
    success: false,
    message: 'API端点不存在'
  })
})

// 错误处理中间件
app.use((error, req, res, next) => {
  console.error('服务器错误:', error)
  res.status(500).json({
    success: false,
    message: '服务器内部错误'
  })
})

// 启动服务器
app.listen(PORT, () => {
  console.log(`🚀 橘子小说后备服务器启动成功!`)
  console.log(`📍 服务地址: http://localhost:${PORT}`)
  console.log(`🔧 运行模式: 内存存储 (无需数据库)`)
  console.log(`⚠️  注意: 这是开发测试服务器，数据不会持久化`)
  console.log(`\n📖 测试账号:`)
  console.log(`   管理员: admin / admin123`)
  console.log(`   普通用户: reader / 123456`)
  console.log(`\n🌐 API文档: http://localhost:${PORT}/api/health`)
})

// 优雅关闭
process.on('SIGTERM', () => {
  console.log('\n🛑 接收到终止信号，正在关闭服务器...')
  process.exit(0)
})

process.on('SIGINT', () => {
  console.log('\n🛑 接收到中断信号，正在关闭服务器...')
  process.exit(0)
})
